<?php
/**
 * Created by PhpStorm.
 * User: sunny
 * 尽人事，听天命
 * Date: 2017/6/25
 * Time: 13:55
 */
namespace app\mobile\controller;

class Wechatbind extends Base{

    public function ajaxWebLogin(){
        if(empty($_GET['qrcode_id'])){
            $this->error_tips('登录失败！请重新扫码。');
        }
        if(!$this->checkLoginQrcode($_GET['qrcode_id'])){
            $this->error_tips('二维码已失效！请重新扫码。');
        }
        if(!empty($this->user_session)){
            if($this->changeLoginQrcode($_GET['qrcode_id'])){
                $this->success_tips('登录成功！');
            }else{
                $this->error_tips('登录失败！请重新扫码。');
            }
        }else{
            return redirect(config('SITE_URL').'/mobile/Login/index?qrcode_id='.$_GET['qrcode_id']);
        }
    }

    public function checkLoginQrcode($qrcode_id){
        $database_login_qrcode = model('LoginQrcode');
        $condition_login_qrcode['id'] = $qrcode_id;
        if($database_login_qrcode->field('`uid`')->where($condition_login_qrcode)->find()){
            return true;
        }else{
            return false;
        }
    }

    public function changeLoginQrcode($qrcode_id){
        $database_login_qrcode = model('LoginQrcode');
        $data_login_qrcode['id'] = $qrcode_id;
        $data_login_qrcode['uid'] = session('user')['uid'];
        if($database_login_qrcode->isUpdate(true)->save($data_login_qrcode)){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 注册过程走的登录
     * @return \think\response\Json
     * created by sunnier<xiaoyao_xiao@126.com>
     */
    public function regWechatLogin(){
        $database_login_qrcode = model('LoginQrcode');
        $condition_login_qrcode['id'] = input('get.qrcode_id');
        if(empty($condition_login_qrcode['id'])){
            echo "未获取到qrcode_id！";die;
        }
        $now_qrcode = $database_login_qrcode->field('`uid`')->where($condition_login_qrcode)->find();
        if (!empty($now_qrcode['uid'])) {
            if ($now_qrcode['uid'] == -1) {
                $condition_login_qrcode['uid'] = input('get.uid');
                $database_login_qrcode->isUpdate(true)->save($condition_login_qrcode);
                echo "登陆成功！";die;
            }
            $result = model('Member')->autologin('id', $now_qrcode['uid']);
            if (empty($result['error_code'])) {
                echo "登陆成功！";die;
            } else if ($result['error_code'] == 1001) {
                echo "没有查找到用户，请重新扫描二维码！！";die;
            } else if ($result['error_code']) {
                echo "登陆失败！";die;
            }
        }else{
            $condition_login_qrcode['uid'] = input('get.uid');
            $database_login_qrcode->isUpdate(true)->save($condition_login_qrcode);
            echo "登陆成功！";die;
        }
    }

}